package hhm.android.main

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.calendar.DateUtil
import hhm.android.library.chart.charts.LineChart
import hhm.android.library.chart.components.*
import hhm.android.library.chart.data.Entry
import hhm.android.library.chart.data.LineData
import hhm.android.library.chart.data.LineDataSet
import hhm.android.library.chart.formatter.IAxisValueFormatter
import hhm.android.library.chart.formatter.IFillFormatter
import hhm.android.library.chart.highlight.Highlight
import hhm.android.library.chart.listener.OnChartValueSelectedListener
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.HttpHelper
import siau.android.base.SBApplication
import siau.android.base.SBBaseActivity
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import siau.android.http.model.GrowTrendResponse
import siau.android.http.model.SeeTrendsRequest
import siau.android.library.KeyString
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class SeeTrendsActivity : SBBaseActivity() {

    private var childId: Int = 0
    private var dataType: Int = 0
    private var startTime: Long = 0
    private var endTime: Long = 0
    lateinit var top: LinearLayout
    lateinit var chart: LineChart
    lateinit var tvTime: TextView
    lateinit var tvKgOrCm: TextView
    lateinit var analyse: TextView
    private var sdsbs: SelectDateSpaceBottomSheet? = null
    private var markViewClass: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_see_trends)
        initTitleWithLine(getString(R.string.see_trends))

        top = findViewById(R.id.activity_see_trends_top)
        chart = findViewById(R.id.activity_see_trends_chart)
        tvTime = findViewById(R.id.activity_see_trends_time)
        tvKgOrCm = findViewById(R.id.activity_see_trends_tv)
        analyse = findViewById(R.id.activity_see_trends_analyse)

        childId = intent.getIntExtra(KeyString.childId, 0)
        dataType = intent.getIntExtra(KeyString.dataType, 0)

        var cla = ""
        if (dataType == OneFragmentInner.PAGE_STATE_WEIGHT) {
            when (SBApplication.userData.weightUnit) {
                WeightClass.KG.msg -> {
                    cla = getString(R.string._kg)
                    markViewClass = getString(R.string.class_kg)
                }
                WeightClass.JIN.msg -> {
                    cla = getString(R.string._jin)
                    markViewClass = getString(R.string.class_jin)
                }
                WeightClass.LB.msg -> {
                    cla = getString(R.string._lb)
                    markViewClass = getString(R.string.class_bang)
                }
            }
        } else {
            when (SBApplication.userData.heightUnit) {
                HeightClass.CM.msg -> {
                    cla = getString(R.string._cm)
                    markViewClass = getString(R.string.class_cm)
                }
                HeightClass.FT.msg -> {
                    cla = getString(R.string._ft)
                    markViewClass = getString(R.string.class_ft)
                }
            }
        }

        if (dataType == 1) {
            tvKgOrCm.text = cla
            analyse.text = getString(R.string.weight_analyse)
        } else {
            tvKgOrCm.text = cla
            analyse.text = getString(R.string.height_analyse)
        }

        analyse.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (chart.data.dataSetCount > 0) {
                    val i = Intent(this@SeeTrendsActivity, DataAnalyseActivity::class.java)
                    i.putExtra(KeyString.childId, childId)
                    i.putExtra(KeyString.type, dataType)
                    startActivity(i)
                }
            }
        })

        val d = Date()
        endTime = d.time

        val sdf = SimpleDateFormat("yyyy/MM/dd")
        val endDate = Date()
        val end = endDate.time
        val sEnd = sdf.format(endDate)
        val startDate = DateUtil.addMonth(endDate, -3)
        val sStart = sdf.format(startDate)
        startTime = startDate.time
        endTime = end
        tvTime.text = "$sStart-$sEnd"

        val sdsbs = SelectDateSpaceBottomSheet(this) { start, end, text ->
            tvTime.text = text
            startTime = start
            endTime = end
            getData()
        }

        top.setOnClickListener {
            sdsbs.show()
        }

        // no description text
        chart.description.isEnabled = false

        // enable touch gestures
        chart.setTouchEnabled(true)

        // enable scaling and dragging
        chart.isDragEnabled = true
        chart.setScaleEnabled(true)
        //X轴可以缩放 Y轴禁止缩放
        chart.isScaleXEnabled = true
        chart.isScaleYEnabled = false
        chart.setDrawGridBackground(false)
        chart.isHighlightPerDragEnabled = true

        //点击的时候展示
        val mv = MyMarkerView(this, dataType, markViewClass)
        mv.chartView = chart
        chart.marker = mv

        chart.setBackgroundColor(Color.WHITE)

        chart.setPinchZoom(true)
        chart.setMaxVisibleValueCount(7)

        val l = chart.legend
        l.isEnabled = false

        val xAxis = chart.xAxis
        xAxis.setAvoidFirstLastClipping(true)
        xAxis.setDrawLimitLinesBehindData(true)
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textSize = 10f
        xAxis.textColor = Color.WHITE
//        xAxis.setDrawAxisLine(false)
        xAxis.setDrawGridLines(false)
        xAxis.textColor = ContextCompat.getColor(this, R.color.color_333333)
        xAxis.setCenterAxisLabels(false)
        xAxis.granularity = 1f // one day

        xAxis.valueFormatter = object : IAxisValueFormatter {
            private val mFormat = SimpleDateFormat("MM-dd", Locale.ENGLISH)
            override fun getFormattedValue(value: Float, axis: AxisBase?): String? {
                val millis = TimeUnit.DAYS.toMillis(value.toLong())
                return mFormat.format(Date(millis))
            }
        }

        val leftAxis: YAxis = chart.axisLeft
        leftAxis.isEnabled = false
        val rightAxis: YAxis = chart.axisRight
        rightAxis.isEnabled = false

        chart.setBorderColor(R.color.white)

        getData()
    }

    private fun getData() {
        showLoadingFragment(R.id.activity_see_trends_fl)
        val r = SeeTrendsRequest(startTime, endTime, childId, dataType)
        HttpHelper().growTrend(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            removeLoadingFragment()
            setData(it)
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun setData(it: GrowTrendResponse) {
        val list = it.list
        val sdf = SimpleDateFormat("yyyy-MM-dd")

        val values: ArrayList<Entry> = ArrayList<Entry>()
        ArrayList<String>()
        for (i in 0 until list.size) {
            val date = sdf.parse(list[i].recordDate)
            val l = TimeUnit.MILLISECONDS.toDays(date.time)
            val e = Entry(l.toFloat() + 1, list[i].recordValue.toFloat())
            e.data = list[i]
            values.add(e)
        }

        // create a dataset and give it a type
        val set1 = LineDataSet(values, "DataSet 1")
        set1.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
        //icons指上面的星星
        set1.setDrawCircles(true)
        set1.setDrawIcons(true)
//        set1.setDrawCircleHole(false)
        set1.lineWidth = 3f
        set1.circleRadius = 3f
        set1.formLineWidth = 0f
        set1.formSize = 15f
        set1.valueTextSize = 9f

        //背景渐变色
        val drawable = ContextCompat.getDrawable(this, R.drawable.fade_blue)
        set1.fillDrawable = drawable

        set1.setDrawFilled(true)
        set1.fillFormatter = IFillFormatter { dataSet, dataProvider -> chart.axisLeft.axisMinimum }

        val data = LineData(set1)
        chart.data = data
        chart.invalidate()
    }

    override fun onDestroy() {
        super.onDestroy()
        sdsbs?.dismiss()
    }
}